package cn.javacart.jopencart.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import com.jfinal.kit.StrKit;
import com.jfinal.upload.MultipartRequest;

/**
 * Opencat转换器，Content-Type处理
 * @author farmer
 *
 */
public class JOpencartPhpUrlFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {}
	
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		final HttpServletRequest req = (HttpServletRequest) request;
		if(StrKit.notBlank(req.getHeader("Content-Type")) && req.getHeader("Content-Type").startsWith("multipart/form-data")){
			chain.doFilter(new MultipartRequest(req){
				@Override
				public String getRequestURI() {
					return convertRoute(req);
				}
			}, response);
		}
		else{
			chain.doFilter(new HttpServletRequestWrapper(req){
				@Override
				public String getRequestURI() {
					return convertRoute(req);
				}
			}, response);
		}
	}

	@Override
	public void destroy() {
	}

	/**
	 * 路由转换
	 * @param request
	 * @return
	 */
	private String convertRoute(HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		if("/".equals(requestURI)){
			requestURI = "/index.php";
		}
		if("/index.php".equals(requestURI)){
			String route = request.getParameter("route");
			if("".equals(route)||route == null){
				route = "/common/home";
			}
			if(!route.startsWith("/")){
				route = "/".concat(route);
			}
			return route; 
		}
		return requestURI;
	}

}
